
import router from '@/router'
import localCache from '@/utils/cache'
import { Module } from 'vuex'
import { login } from '@/api'
import { message } from 'ant-design-vue'
import { selfMenu } from '@/utils/public'
const autoModule: Module<any, any> = {
  namespaced: true,
  state () {
    return {
      accessToken: '',
      userInfo: {},
      userMenu: []
    }
  },
  getters: {},
  mutations: {
    SET_TOKEN (state, token: string) {
      state.token = token
    },
    SET_USERINFO (state, userInfo: any) {
      state.userInfo = userInfo
    },
    SET_USER_MENU (state, userMenu: any) {
      state.userMenu = userMenu
    }
  },
  actions: {
    async AUTO_ACTION ({ commit }, plylod) {
      // 登录逻辑
      const autoResult: any = await login(plylod)
      const { data: { status, msg, obj } } = autoResult
      if (status === 200) {
        const { admin, token } = obj
        commit('SET_TOKEN', token)
        localCache.setCache('token', token)
        commit('SET_USERINFO', admin)
        localCache.setCache('userInfo', admin)
        commit('SET_USER_MENU', selfMenu)
        localCache.setCache('userMenu', selfMenu)
      } else {
        message.error(msg)
      }
      // 跳到首页
      router.push('/')
    },
    LOAD_LOCAL_DATA ({ commit }) {
      // 除了固化vuex数据，可以在主函数调用加载数据
      const accessToken = localCache.getCache('token')
      if (accessToken) {
        commit('SET_TOKEN', accessToken)
      }
      const userInfo = localCache.getCache('userInfo')
      if (userInfo) {
        commit('SET_USERINFO', userInfo)
      }
      const userMenu = localCache.getCache('userMenu')
      if (userMenu) {
        commit('SET_USER_MENU', userMenu)
      }
    }
  }
}
export default autoModule
